<template>
  <div class="article-list-container">
    <van-pull-refresh v-model="isRefreshLoading" :success-text="successText" :success-duration="1500" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item v-for="(article,index) in articles" :key="index" :article="article"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '@/components/article-item.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      articles: [],
      loading: false, // 加载数据的状态
      finished: false, // 加载完成的状态
      timestamp: null,
      error: false, // 请求失败的状态
      isRefreshLoading: false, // 下拉刷新的状态
      successText: '' // 刷新成功的提示文本
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.articles.push(...results)
        this.loading = false
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道id
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.articles.unshift(...results)
        this.isRefreshLoading = false
        this.successText = `刷新成功，更新了  ${results.length} 条数据`
      } catch (err) {
        this.successText = '刷新失败'
        this.isRefreshLoading = false
      }
    }
  }
}

</script>
<style lang='less' scoped>
.article-list-container {
  height: 79vh;
  overflow-y: auto;
}
</style>
